# -*- coding: utf-8 -*-
"""
Created on Otc. 29 10:30:42 2019
version:v1.0
@author: Binary
ps -ef | grep driver | grep -v grep | awk '{print $2}' | xargs kill
"""
import driverCommon as dC
import os
import time
driver = None

def runscript(script_file_name, paras=None):
    if not paras:
        paras = []
    print("run script [%s] with paras %s:" % (script_file_name, paras))
    fr = open(script_file_name, "r", encoding='utf8')
    lines = fr.readlines()
    i = 0
    delim = ','
    varb = "${var"
    vare = "}"
    for line in lines:
        line = line.replace("\n", "")
        if i == 0:
            rows = line.split(',')
            delim, varb, vare = rows
            delim = delim if delim != "" else ','
            varb = varb if varb != "" else '${var'
            vare = vare if vare != "" else '}'
        else:
            j = 0
            if line[:1] == '#' or len(line.replace(" ", "").replace("\t", "")) == 0:
                continue
            for var in paras:
                # print("replace para[%s%s%s]" % (varb, j, vare))
                line = line.replace("%s%s%s" % (varb, j, vare), var)
                # .replace("False", "")
                j += 1
            rows = line.split(delim)
            if len(rows) > 0:
                cmd, *extra = rows
                if hasattr(dC, cmd):
                    do = getattr(dC, cmd)
                    msg = "step %s:%s%s" % (i, cmd, tuple(extra))
                    print(msg.replace(',)', ')'))
                    do(*extra)
                else:
                    print("step %s:undefined command [%s%s] in code,please check it!" % (i, cmd, tuple(extra)))
            else:
                print("step %s:error line[%s]" % (i, line))
        i += 1


def looprunscript(script_file_name, param_file_name):
    fr = open(param_file_name, "r", encoding='utf8')
    lines = fr.readlines()
    for line in lines:
        line = line.replace("\n", "")
        runscript(script_file_name,line.split(','))


if __name__ == '__main__':
    print("[%s] begin at %s" % (os.path.basename(__file__).split('.')[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
    runscript("test.wds", ['刘亦菲'])
    # looprunscript("test.wds", "test.par")
    print("[%s] finish at %s" % (os.path.basename(__file__).split('.')[0], time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
